package woaini.wind.bot.command.qylc.app.ticket.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSONPath;
import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import woaini.wind.bot.core.exception.BotAssertTool;
import woaini.wind.bot.core.exception.enums.BotExceptionType;

import java.time.LocalDate;
import java.util.Map;

@UtilityClass
@Slf4j
public class QylcTicketApi {

  public static final String UAA_URL = "http://119.1.174.231:13800/api/platform-cloud-uaa";

  public static final String TICKET_URL =
      "http://119.1.174.231:13800/api/platform-cloud-ticket-system";

  /**
   * username:system password:123456 verificationCode: grant_type:password
   * client_id:14a9cf797931430896ad13a6b1855611 client_secret:a05fe1fc50ed42a4990c6c6fc4bec398
   */
  public static final String username = "system";

  public static final String password = "supersystem@2025";

  public static final String grant_type = "password";
  public static final String client_id = "14a9cf797931430896ad13a6b1855611";
  public static final String client_secret = "a05fe1fc50ed42a4990c6c6fc4bec398";

  public static String TOKEN = null;

  public String login() {
    String url = UAA_URL + "/oauth2/token";

    Map<String, String> formMapStr =
        Map.of(
            "username",
            username,
            "password",
            password,
            "grant_type",
            grant_type,
            "client_id",
            client_id,
            "client_secret",
            client_secret,
            "verificationCode",
            "");

    String body =
        HttpRequest.post(url)
            .header("Content-Type", "application/x-www-form-urlencoded")
            .formStr(formMapStr)
            .execute()
            .body();

    TOKEN = JSONPath.extract(body, "$.access_token").toString();
    return TOKEN;
  }


  /**
   * 查询订单信息
   * @param cardNo 卡号
   * @author yefeng
   * {@date 2025-06-12 11:17:31}
   * @since 1.0
   * @return {@link String }
   */
  public String searchTicket(String cardNo){


    String url = TICKET_URL + "/order/queryByPage";

    LocalDate endDate = LocalDate.now();
    LocalDate startDate = LocalDate.now().plusDays(-10);

    String reqBody =
        STR."""
    {
        "pageNumber": 0,
        "pageSize": 10,
        "orderStatusRange": [],
        "orderStatusRange-op": "in",
        "travelDateRange": [
            "\{startDate}",
            "\{endDate}"
        ],
        "travelDateRange-op": "bt",
        "certNo": "\{cardNo}",
        "certNo-op": "eq",
        "properties": [
            "createTime"
        ],
        "direction": "DESC"
    }
    """;

    HttpRequest request = HttpRequest.post(url)
      .header("Content-Type", "application/json")
      .header("Authorization", "Bearer " + TOKEN)
      .body(reqBody);

   return commonPost(request,false);
  }

  /**
   * 获取凭证信息
   * @param orderNo 订单号
   * @param cardNo 卡号
   * @author yefeng
   * {@date 2025-06-12 11:17:53}
   * @since 1.0
   * @return {@link String }
   */
  public String getVoucherInfo(String orderNo,String cardNo){

    String url = TICKET_URL + STR."/order/\{orderNo}/info";

    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }

  /**
   * 获取 Sub 凭证信息
   * @param masterVouchCode Master 担保代码
   * @author yefeng
   * {@date 2025-06-12 11:51:57}
   * @since 1.0
   * @return {@link String }
   */
  public String getSubVoucherInfo(String masterVouchCode){

    String url = TICKET_URL + STR."/order/orderVouch?masterVouchCode=\{masterVouchCode}&masterVouchCode-op=eq&direction=DESC" +
      "&properties=createTime";

    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }

  /**
   * 获取过闸情况
   * @param cardNo 卡号
   * @author yefeng
   * {@date 2025-06-12 11:58:20}
   * @since 1.0
   * @return {@link String }
   */
  public String gatePassSituationByCardNo(String cardNo){
    String url = TICKET_URL + "/log/checkTicket?page=0&size=10&startTimeEndTime=&voucherCode=&searchKey" +
      STR."=\{cardNo}&properties=createTime&direction=DESC&pageNumber=0";
    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }


  public String gatePassSituationByVoucher(String voucherCode){
    String url = TICKET_URL + STR."/log/checkTicket?page=0&size=10&startTimeEndTime=&voucherCode=\{voucherCode}&searchKey=&properties" +
      "=createTime&direction=DESC&pageNumber=0";
    HttpRequest httpRequest = HttpRequest.get(url);
    return commonPost(httpRequest,false);
  }


  /**
   * zfb out face
   * @param vid 视频
   * @author yefeng
   * {@date 2025-06-20 14:26:34}
   * @since 1.0
   * @return {@link String }
   */
  public String zfbOutFace(String vid){

    String url = TICKET_URL + "/app/api/open/public/zfb/face/deleteUserFace";

    String reqBody = STR."""
    {
        "vid": "\{vid}"
    }
    """;

    HttpRequest httpRequest = HttpRequest.post(url)
      .header("Content-Type", "application/json")
      .body(reqBody);
    return commonPost(httpRequest,false);
  }

  /**
   * 创建订单
   * @param name 名字
   * @param cardNo 卡号
   * @author yefeng
   * {@date 2025-06-12 17:25:05}
   * @since 1.0
   * @return {@link String }
   */
  public String createTestOrder(String name, String cardNo,String authCode,String cardType){

    String url = TICKET_URL + "/order";

    String today = LocalDate.now().toString();
    String reqBody = STR."""
    {
        "contactName": "\{name}",
        "contactTel": "15934729199",
        "salesSiteId": "01JVVN83R2ZD4AYYP2MKSNS31Y",
        "items": [
            {
                "buySupply": 1,
                "realNames": [
                    {
                        "cardNo": "\{cardNo}",
                        "cardType": "\{cardType}",
                        "name": "\{name}",
                        "phone": "15934729199"
                    }
                ],
                "salesGroupAuthCode": "\{authCode}",
                "useDate": "\{today}"
            }
        ],
        "useDate": "\{today}",
        "userRemark": "测试单"
    }
    """;

    HttpRequest httpRequest = HttpRequest.post(url)
      .header("Content-Type", "application/json")
      .body(reqBody);
    return commonPost(httpRequest,false);
  }

  public String payTestOrder(String orderNo){
    String url = TICKET_URL + STR."/order/\{orderNo}/pay/SYSTEM_PAY";
    HttpRequest httpRequest = HttpRequest.put(url);
    return commonPost(httpRequest,false);
  }

  /**
   * 公共请求
   * @param request 请求
   * @author yefeng
   * {@date 2025-06-12 11:17:41}
   * @since 1.0
   * @return {@link String }
   */
  private String commonPost(HttpRequest request,Boolean reply){

    try {
      request.header("Authorization", "Bearer " + TOKEN);
      HttpResponse execute = request.execute();

      int status = execute.getStatus();
      if (!reply && status == 401) {
        TOKEN = login();
        return commonPost(request,true);
      }else if (status == 200){
        return execute.body();
      }else {
        String message = Convert.toStr(JSONPath.extract(execute.body(), "$.message"));
        BotAssertTool.isActualTrue(true, BotExceptionType.BOT_SERVICE, "请求异常:"+ message);
        return null;
      }
    } catch (HttpException e) {
      log.error("请求异常", e);
      BotAssertTool.isActualTrue(true, BotExceptionType.BOT_SERVICE, "请求异常:未知异常");

      return null;
    }
  }



}
